package com.htgd.gardenexpo.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.htgd.gardenexpo.dto.WxUserCollectDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.CollectQuery;
import com.htgd.gardenexpo.page.PageBase;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * <p>
 * 用户收藏表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-26
 */
@RestController
@RequestMapping("/api/wxCollect")
@Api(tags = "用户收藏")
@Slf4j
public class WxUserCollectController {

    @Autowired
    private WxUserCollectService wxUserCollectService;

    @Autowired
    private GeConSceneService geConSceneService;

    @Autowired
    private GeConSportService geConSportService;

    @Resource
    private GeConNewsService geConNewsService;

    @Autowired
    private GeConHealthyService geConHealthyService;

    @PostMapping("/add")
    @Transactional
    @ApiOperation("新增")
    public synchronized CommonResult<JSONObject> add (@RequestBody WxUserCollectDTO wxUserCollect,
                                         HttpServletRequest request){
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        log.info("用户收藏-新增：{},{}",openId,wxUserCollect);
        Boolean collect = wxUserCollectService.isLike(openId, wxUserCollect.getTypeId(),wxUserCollect.getType());
        if(collect.equals(false)){
            //新增
            WxUserCollect wxUserCollect1 = new WxUserCollect();
            wxUserCollect1.setType(wxUserCollect.getType());
            wxUserCollect1.setUserId(openId);
            wxUserCollect1.setTypeId(wxUserCollect.getTypeId());
            wxUserCollectService.save(wxUserCollect1);
        }
        return CommonResult.success("收藏成功");
    }

    @GetMapping("/details")
    @ApiOperation("详情")
    public CommonResult<WxUserCollect> details (int id){
        CommonResult<WxUserCollect> result = new CommonResult<>();
        WxUserCollect wxUserCollect = wxUserCollectService.getById(id);
        try {
            result.setCode(200);
            result.setMessage("查询成功");
            result.setData(wxUserCollect);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;

    }

    @PostMapping(value = "/delete")
    @Transactional
    @ApiOperation("删除")
    public synchronized CommonResult<JSONObject> delete(@RequestBody WxUserCollectDTO collect,
                                           HttpServletRequest request) {
        CommonResult<JSONObject> result = new CommonResult<>();
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        ExecutorService executor = Executors.newFixedThreadPool(10);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            WxUserCollect wxUserCollect = wxUserCollectService.getIdByOpenIdAndTypeId(openId,collect.getTypeId());
            if(Objects.nonNull(wxUserCollect)) {
                if (Objects.equals(wxUserCollect.getType(), "scene")) {
                    GeConScene geConScene = geConSceneService.getById(Integer.valueOf(wxUserCollect.getTypeId()));
                    geConScene.setLikeNumber(geConScene.getLikeNumber() - 1);
                    geConSceneService.updateById(geConScene);
                } else if (Objects.equals(wxUserCollect.getType(), "news")) {
                    GeConNews geConNews = geConNewsService.queryById(Integer.valueOf(wxUserCollect.getTypeId()));
                    geConNews.setLikeNumber(geConNews.getLikeNumber() - 1);
                    geConNewsService.update(geConNews);
                } else if (Objects.equals(wxUserCollect.getType(), "sport")) {
                    GeConSport geConSport = geConSportService.getById(wxUserCollect.getTypeId());
                    if (Objects.nonNull(geConSport)) {
                        geConSport.setLikeNumber(geConSport.getLikeNumber() - 1);
                        geConSportService.updateById(geConSport);
                    }
                } else if (Objects.equals(wxUserCollect.getType(), "healthy")) {
                    GeConHealthy geConHealthy = geConHealthyService.getById(wxUserCollect.getTypeId());
                    if (Objects.nonNull(geConHealthy)) {
                        geConHealthy.setLikeNumber(geConHealthy.getLikeNumber() - 1);
                        geConHealthyService.updateById(geConHealthy);
                    }
                }
            }
            return "操作结果";
        }, executor);
        LambdaQueryWrapper<WxUserCollect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WxUserCollect::getUserId,openId);
        lambdaQueryWrapper.eq(WxUserCollect::getTypeId,collect.getTypeId());
        wxUserCollectService.remove(lambdaQueryWrapper);
        result.setCode(200);
        result.setMessage("取消收藏");
        return result;
    }


    @GetMapping(value = "/getMyCollectList")
    @ApiOperation("获取我的收藏（喜欢）")
    public CommonResult<List<HashMap>> getMyCollectList(CollectQuery collectQuery, HttpServletRequest request) {
        CommonResult<List<HashMap>> result = new CommonResult<>();
        List<HashMap> list = wxUserCollectService.getMyCollectList(collectQuery,request);
        result.setCode(200);
        result.setData(list);
        result.setMessage(String.valueOf(list.size()));
        return result;
    }

}
